<?php

namespace App\Models;

use Illuminate\Support\Arr;
use Kalnoy\Nestedset\NodeTrait;
use Spatie\Activitylog\Traits\LogsActivity;

class Category extends Base
{
    use NodeTrait, LogsActivity;

    /**
     * 自定义操作日志 说明
     * @param $eventName
     * @return string
     */
    public function getDescriptionForEvent(string $eventName): string
    {
        if (in_array($eventName, ['created', 'deleted', 'updated'])) {
            switch ($eventName) {
                case 'created':
                    return '创建商品类别:' . ($this['name'] ?? '');
                case 'deleted':
                    return sprintf('删除商品类别: %s', $this['name'] ?? '');
                case 'updated':
                    if (!$this->wasChanged()) {
                        return '';
                    }

                    $changesMap = ['name' => '类别名称', 'sort_id' => '排序'];
                    $changes = [];
                    foreach (Arr::only($this->getChanges(), ['name', 'sort_id']) as $field => $value) {
                        $changes[] = [
                            'field' => $changesMap[$field],
                            'text' => $this->getOriginal($field) . ' 改为 ' . $value
                        ];
                    }

                    return sprintf('编辑商品类别: %s', array_reduce($changes, fn ($init, $item) => $init . ($item['field'] . ' ' . $item['text']) . '; ', ''));
            }
        }

        return '';
    }
}
